from rest_framework.generics import ListAPIView,RetrieveAPIView
from rest_framework_extensions.cache.mixins import ListCacheResponseMixin

from .serializers import NewsCategorySerializer, NewsSerializer, NewsDetailSerializer
from .models import NewsCategory, News


# /
class NewsCategoryView(ListCacheResponseMixin, ListAPIView):
    """新闻分类视图"""
    serializer_class = NewsCategorySerializer
    queryset = NewsCategory.objects.all().order_by('sequence')


# /newslist/(?P<category_id>\d+)/
class NewsView(ListAPIView):
    """新闻列表视图"""
    serializer_class = NewsSerializer

    def get_queryset(self):
        category_id = self.kwargs['category_id']
        if category_id == '0':
            # 返回热门
            queryset = News.objects.filter(is_delete=False).order_by('-clicks').select_related('author')
        else:
            queryset = News.objects.filter(category_id=category_id, is_delete=False).order_by('-create_time').select_related('author')
        return queryset


# /news/(?P<news_id>\d+)/
class NewsDetailView(ListAPIView):
    """新闻详情"""
    serializer_class = NewsDetailSerializer

    def get_queryset(self):
        news_id = self.kwargs['news_id']
        queryset = News.objects.filter(id=news_id).prefetch_related("author__comment_set__comment_set")
        return queryset




    

